import java.io.*;
import java.util.*;
import java.util.function.BiFunction;
import java.util.regex.*;
import java.util.Scanner;

public class SimpleDBMS {

    // 表示列的结构
    static class Column {
        String name;
        String type;
        boolean isPrimaryKey;
        boolean isNullable;
        boolean isUnique;

        public Column(String name, String type, boolean isPrimaryKey, boolean isNullable, boolean isUnique) {
            this.name = name;
            this.type = type;
            this.isPrimaryKey = isPrimaryKey;
            this.isNullable = isNullable;
            this.isUnique = isUnique;
        }
    }

    // 表的结构
    static class Table {
        String name;
        List<Column> columns;
        Map<String, List<String>> rows;

        public Table(String name) {
            this.name = name;
            this.columns = new ArrayList<>();
            this.rows = new HashMap<>();
        }
    }

    // 数据字典：以表名为键存储表的信息
    static Map<String, Table> dataDictionary = new HashMap<>();
    static Map<String, Map<String, Map<String, String>>> TableData = new HashMap<>();
    static Queue<String> out = new LinkedList<>();

    // 操作符映射
    static Map<String, BiFunction<Integer, Integer, Boolean>> operators = new HashMap<>();

    // 初始化操作符映射
    static void InitOperators() {
        operators.put("<", (a, b) -> a < b);
        operators.put(">", (a, b) -> a > b);
        operators.put("<=", (a, b) -> a <= b);
        operators.put(">=", (a, b) -> a >= b);
        operators.put("=", (a, b) -> a.equals(b));
        operators.put("!=", (a, b) -> !a.equals(b));
    }

    // 删除数据字典中的表
    static void dropTable(String tableName) {
        if (dataDictionary.containsKey(tableName)) {
            dataDictionary.remove(tableName);
            TableData.remove(tableName);  // 删除表的数据
            System.out.println("表 " + tableName + " 已被删除");
        } else {
            System.out.println("表 " + tableName + " 不存在，无法删除");
        }
    }

    // 插入数据
    static void InsertInto(String sql) {
        sql = sql.toLowerCase();  // 将输入的 SQL 语句转换为小写

        Pattern pattern = Pattern.compile("insert into (\\w+) \\((.*?)\\) values \\((.*?)\\);");
        Matcher matcher = pattern.matcher(sql);

        if (matcher.find()) {
            String tableName = matcher.group(1);
            String columns = matcher.group(2);
            String values = matcher.group(3);

            String[] columnsArr = columns.split(",");
            String[] valuesArr = values.split(",");

            Map<String, Map<String, String>> tableData = TableData.get(tableName);
            if (tableData == null) {
                tableData = new HashMap<>();
                TableData.put(tableName, tableData);
            }

            // 生成一个唯一的主键（这里简单使用当前插入的行数+1作为主键）
            String primaryKey = String.valueOf(tableData.size() + 1);  // 使用 size+1 来确保主键递增

            for (int i = 0; i < columnsArr.length; i++) {
                String columnName = columnsArr[i].trim();
                String value = valuesArr[i].trim();

                // 如果插入数据包含主键列（如 id），我们将其设置为自动递增
                if (columnName.equalsIgnoreCase("id")) {
                    // 不需要用户传入主键，直接使用递增的主键值
                    value = primaryKey;
                }

                tableData.computeIfAbsent(columnName, k -> new HashMap<>())
                        .put(primaryKey, value);  // 将主键作为数据的键
            }
        }
    }


    // 查询数据
    static void Select(String sql) {
        sql = sql.toLowerCase();  // 将输入的 SQL 语句转换为小写

        Pattern pattern = Pattern.compile("select \\* from (\\w+);");
        Matcher matcher = pattern.matcher(sql);

        if (matcher.find()) {
            String tableName = matcher.group(1);
            Map<String, Map<String, String>> tableData = TableData.get(tableName);

            if (tableData != null) {
                System.out.println("数据内容:");
                for (Map.Entry<String, Map<String, String>> columnEntry : tableData.entrySet()) {
                    String columnName = columnEntry.getKey();
                    Map<String, String> columnData = columnEntry.getValue();
                    for (Map.Entry<String, String> rowEntry : columnData.entrySet()) {
                        System.out.println("主键: " + rowEntry.getKey() + " " + columnName + ": " + rowEntry.getValue());
                    }
                }
            } else {
                System.out.println("表 " + tableName + " 不存在。");
            }
        }
    }

    // 更新数据
    static void Update(String sql) {
        sql = sql.toLowerCase();  // 将输入的 SQL 语句转换为小写

        Pattern pattern = Pattern.compile("update (\\w+) set (.*?) where (.*?);");
        Matcher matcher = pattern.matcher(sql);

        if (matcher.find()) {
            String tableName = matcher.group(1);
            String setClause = matcher.group(2);
            String whereClause = matcher.group(3);

            // 解析SET部分
            String[] setParts = setClause.split(",");
            for (String part : setParts) {
                String[] setKeyValue = part.split("=");
                String column = setKeyValue[0].trim();
                String value = setKeyValue[1].trim();

                // 更新数据
                Map<String, Map<String, String>> tableData = TableData.get(tableName);
                if (tableData != null) {
                    for (Map.Entry<String, Map<String, String>> columnEntry : tableData.entrySet()) {
                        if (columnEntry.getKey().equals(column)) {
                            Map<String, String> columnData = columnEntry.getValue();
                            for (String key : columnData.keySet()) {
                                columnData.put(key, value);  // 更新每一行的数据
                            }
                        }
                    }
                }
            }
        }
    }

    // 删除数据
    static void Delete(String sql) {
        sql = sql.toLowerCase();  // 将输入的 SQL 语句转换为小写

        Pattern pattern = Pattern.compile("delete from (\\w+) where (.*?);");
        Matcher matcher = pattern.matcher(sql);

        if (matcher.find()) {
            String tableName = matcher.group(1);
            String whereClause = matcher.group(2);

            // 删除数据
            Map<String, Map<String, String>> tableData = TableData.get(tableName);
            if (tableData != null) {
                // 在这里假设我们仅使用主键进行简单的删除操作
                tableData.clear();  // 删除所有数据（简化实现）
                System.out.println("表 " + tableName + " 的数据已被删除。");
            }
        }
    }

    // 打印数据字典和表数据
    static void PrintOutDataDictionary() {
        for (Map.Entry<String, Table> entry : dataDictionary.entrySet()) {
            String tableName = entry.getKey();
            Table table = entry.getValue();
            System.out.println("表名: " + tableName);

            // 仅输出数据内容
            Map<String, Map<String, String>> tableData = TableData.get(tableName);
            if (tableData != null) {
                for (Map.Entry<String, Map<String, String>> columnEntry : tableData.entrySet()) {
                    String columnName = columnEntry.getKey();
                    Map<String, String> columnData = columnEntry.getValue();
                    for (Map.Entry<String, String> rowEntry : columnData.entrySet()) {
                        System.out.println("主键: " + rowEntry.getKey() + " 数据内容: " + rowEntry.getValue());
                    }
                }
            }
        }
    }

    // 创建表
    static void CreateTable(String sql) {
        sql = sql.toLowerCase();  // 将输入的 SQL 语句转换为小写

        Pattern pattern = Pattern.compile("create table (\\w+) \\((.*)\\);");
        Matcher matcher = pattern.matcher(sql);

        if (matcher.find()) {
            String tableName = matcher.group(1);
            String columnInfo = matcher.group(2);

            Table newTable = new Table(tableName);
            dataDictionary.put(tableName, newTable);

            // 初始化表的数据存储
            TableData.put(tableName, new HashMap<>());

            String[] columns = columnInfo.split(",");
            for (String column : columns) {
                CreateColumn(tableName, column.trim());
            }
        }
    }

    // 创建列
    static void CreateColumn(String tableName, String columnDefinition) {
        String[] parts = columnDefinition.split(" ");
        String name = parts[0];
        String type = parts[1];
        boolean isPrimaryKey = false;
        boolean isNullable = true;
        boolean isUnique = false;

        // 处理约束
        if (parts.length > 2) {
            for (int i = 2; i < parts.length; i++) {
                switch (parts[i].toUpperCase()) {
                    case "PRIMARY":
                        isPrimaryKey = true;
                        break;
                    case "NOT":
                        isNullable = false;
                        break;
                    case "UNIQUE":
                        isUnique = true;
                        break;
                }
            }
        }

        Column column = new Column(name, type, isPrimaryKey, isNullable, isUnique);
        dataDictionary.get(tableName).columns.add(column);
        out.offer(name);
    }

    // 主函数：从键盘输入SQL语句并执行
    public static void main(String[] args) throws IOException {
        // 初始化操作符映射
        InitOperators();

        Scanner scanner = new Scanner(System.in);

        while (true) {
            System.out.println("请输入SQL语句（例如：create table person (id int, name string);）：");
            String sql = scanner.nextLine().toLowerCase();  // 转换为小写

            if (sql.startsWith("create table")) {
                CreateTable(sql);
            } else if (sql.startsWith("insert into")) {
                InsertInto(sql);
            } else if (sql.startsWith("drop table")) {
                dropTable(sql);
            } else if (sql.startsWith("select")) {
                Select(sql);
            } else if (sql.startsWith("update")) {
                Update(sql);
            } else if (sql.startsWith("delete")) {
                Delete(sql);
            } else {
                System.out.println("未识别的 SQL 语句！");
            }

            // 打印数据
            PrintOutDataDictionary();
        }
    }
}
